/**
 *******************************************************************************
 * @FileName  : critical.c
 * @Author    : GaoQiu
 * @CreateDate: 2020-05-18
 * @Copyright : Copyright(C) GaoQiu
 *              All Rights Reserved.
 *******************************************************************************
 *
 * The information contained herein is confidential and proprietary property of
 * GaoQiu and is available under the terms of Commercial License Agreement
 * between GaoQiu and the licensee in separate contract or the terms described
 * here-in.
 *
 * This heading MUST NOT be removed from this file.
 *
 * Licensees are granted free, non-transferable use of the information in this
 * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************
 */
#include "critical.h"
#include "cmsis/cmsis_compiler.h"

#include "track.h"

/* Critical Section(CS) nesting level. */
volatile uint32_t csNesting = 0;

static _inline_ uint32_t disable_irq(void)
{
#if 1
	 uint32_t state = __get_PRIMASK();
	 __disable_irq();

	return state;
#else
	__disable_irq();
	return 0;
#endif
}

static _inline_ void enable_irq(uint32_t state)
{
#if 1
	if (state != 0U) {
		return;
	}
	__enable_irq();

#else
	UNUSED(state);
	__enable_irq();
#endif
}

RAM_CODE uint32_t EnterCritical(void)
{
	uint32_t state = 0;
	if(csNesting == 0){
		state = disable_irq();
	}
	csNesting++;

	return state;
}

RAM_CODE void ExitCritical(uint32_t state)
{
	if(csNesting){
		csNesting--;
	}
	if(csNesting == 0){
		enable_irq(state);
	}
}

